import store from '@/store/store.js'
import {analysisAddress} from "@/api/entrance.js"
//验证是否为空
function isEmpty(bodys) {
	for (let body of bodys) {
		if (!body.value) {
			return {
				success: false,
				msg: body.type + '不能为空'
			}
		}
	}
	return {
		success: true
	}
}
//统一提示方便全局修改
function msg(title, duration = 3000, mask = false, icon = 'none', position = 'center') {
	if (Boolean(title) === false) {
		return;
	}
	uni.showToast({
		title,
		duration,
		mask,
		icon,
		position
	});
}
//验证url
function expressionUrl(url) {
	var Expression = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/;
	var objExp = new RegExp(Expression);
	if (objExp.test(url) == true) {
		return true;
	} else {
		return false;
	}
}
//验证登录设备
function systemInfo() {
	if (window) {
		// let ua = window.navigator.userAgent.toLowerCase();
		// if (ua.match(/MicroMessenger/i) == 'micromessenger') {
		//     console.log("微信打开") // 微信中打开
		// } else {
		//     console.log("普通浏览器") // 普通浏览器中打开
		// }
		return "browser";
	} else {
		// let platform = uni.getSystemInfoSync().platform;
		// if (platform == 'ios') {
		// 	console.log("ios")
		// } else if (platform == 'android') {
		// 	console.log("android")
		// }
		return "app";
	}

}
//判断浏览器类型
function browserType() {
	let ua = window.navigator.userAgent.toLowerCase();
	if (ua.match(/MicroMessenger/i) == 'micromessenger') {
		return 'wx';
	}
	let isSafari = ua.indexOf("Safari") > -1 && ua.indexOf("Chrome") == -1;
	if (isSafari) {
		return 'safari'
	} else {
		return 'other'
	}
}
//禁止调试
function doCheck(a) {
	if (("" + a / a)["length"] !== 1 || a % 20 === 0) {
		(function() {}
			["constructor"]("debugger")())
	} else {
		(function() {}
			["constructor"]("debugger")())
	}
	doCheck(++a)
}
// 禁止 pc端访问
function prohibitDebug() {
	//平台、设备和操作系统 
	var system = {
		win: false,
		mac: false,
		xll: false
	};
	//检测平台
	var p = navigator.platform;
	system.win = p.indexOf("Win") == 0;
	system.mac = p.indexOf("Mac") == 0;
	system.x11 = (p == "X11") || (p.indexOf("Linux") == 0);
	if (system.win || system.mac || system.xll) {
		// window.location.href = "";
	}
	//禁止右键
	document.oncontextmenu = function(e) {
		return false
	}
	//禁止debug
	try {
		doCheck(0)
	} catch (err) {}
}
//截取小数
function sliceNumber(num, dig) {
	if (typeof num === 'number') {
		num = String(num);
	}
	if (typeof dig === 'string') {
		dig = Number(dig);
	}
	if (num.includes('.')) {
		return Number(num.split('.')[0] + '.' + num.split('.')[1].slice(0, dig));
	} else {
		return Number(num);
	}
}
//转为unicode 编码  
function encodeUnicode(str) {
	var res = [];
	for (var i = 0; i < str.length; i++) {
		res[i] = ("00" + str.charCodeAt(i).toString(16)).slice(-4);
	}
	return "\\u" + res.join("\\u");
}
// 解码  
function decodeUnicode(str) {
	str = str.replace(/\\/g, "%");
	return unescape(str);
}
//随机数
function randomStr() {
	let str = "qwertyu12345iopasdfgh67890jklzxcvbnm";
	let result = '';
	for (let i = 8; i > 0; --i) {
		result += str[Math.floor(Math.random() * str.length)];
	}
	return "0x" + result
}
//睡眠
function sleep(duration) {
	return new Promise(resolve => {
		setTimeout(() => {
			resolve();
		}, duration);
	});
}
//货币类型
function currencyType(type) {
	switch (type) {
		case 1:
			return "探索";
			break;
		case 2:
			return "发布悬赏";
			break;
		case 3:
			return "悬赏回退";
			break;
		case 4:
			return "开通悬赏主";
			break;
		case 5:
			return "续费悬赏主";
			break;
		case 6:
			return "追加悬赏金额";
			break;
		case 7:
			return "追加悬赏名额";
			break;
		case 8:
			return "推荐悬赏";
			break;
		case 9:
			return "完成悬赏";
			break;
		case 10:
			return "内部转账";
			break;
		case 11:
			return "分红质押";
			break;
		case 12:
			return "分红释放";
			break;
	}
};
//算力类型
function powerType(type) {
	switch (type) {
		case 1:
			return "邀请好友";
			break;
		case 2:
			return "签到奖励";
			break;
		case 3:
			return "任务奖励";
			break;
		case 4:
			return "后台充值";
			break;
		case 5:
			return "游戏奖励";
			break;
		case 6:
			return "淘客返利";
			break;
	}
};

function moneyType(type) {
	switch (type) {
		case 1:
			return "领取分红";
			break;
		case 2:
			return "现金提现";
			break;
	}
}

function platformType(type) {
	switch (type) {
		case "taobao":
			return "淘宝";
			break;
		case "tmall":
			return "天猫";
			break;
		case 11:
			return "考拉";
			break;
		case 5:
			return "拼多多";
			break;
		case 10:
			return "苏宁";
			break;
		case 4:
			return "唯品会";
			break;
		case 2:
			return "京东";
			break;
	}
}
//时间戳转日期
function formatDate(value) {
	if (value == null) {
		return '';
	} else {
		let date = new Date(value);
		let y = date.getFullYear(); // 年
		let MM = date.getMonth() + 1; // 月
		MM = MM < 10 ? ('0' + MM) : MM;
		let d = date.getDate(); // 日
		d = d < 10 ? ('0' + d) : d;
		let h = date.getHours(); // 时
		h = h < 10 ? ('0' + h) : h;
		let m = date.getMinutes(); // 分
		m = m < 10 ? ('0' + m) : m;
		let s = date.getSeconds(); // 秒
		s = s < 10 ? ('0' + s) : s;
		return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s;
	}
}
//时间戳转日期
function formatDateDay(value) {
	if (value == null) {
		return '';
	} else {
		let date = new Date(value);
		let y = date.getFullYear(); // 年
		let MM = date.getMonth() + 1; // 月
		MM = MM < 10 ? ('0' + MM) : MM;
		let d = date.getDate(); // 日
		d = d < 10 ? ('0' + d) : d;
		return y + '-' + MM + '-' + d;
	}
}
//时间戳转日期
function formatDateObj(value) {
	if (value == null) {
		return '';
	} else {
		let date = new Date(value);
		let y = date.getFullYear(); // 年
		let MM = date.getMonth() + 1; // 月
		MM = MM < 10 ? ('0' + MM) : MM;
		let d = date.getDate(); // 日
		d = d < 10 ? ('0' + d) : d;
		return {
			date: y + '-' + MM,
			day: d,
			week: "日一二三四五六".charAt(new Date().getDay())
		};
	}
}

function formatTime(value) {
	let s = value - parseInt(Date.now() / 1000)
	let m = parseInt(s / 60)
	let h = parseInt(s / 60 / 60)
	if (h >= 1) {
		return h + '小时'
	} else {
		return m + '分钟'
	}
}

function getPosition(type) {
	return new Promise((resolve, reject) => {
		if (!type) {
			let address = uni.getStorageSync("address");
			if (address) {
				resolve(JSON.parse(address));
				store.commit("setAddress_mutation", JSON.parse(address))
				return;
			}
		}
		// #ifdef APP-PLUS
		uni.getLocation({
			type: 'gcj02',
			geocode: true, //设置该参数为true可直接获取经纬度及城市信息
			success: function(res) {
				resolve(res);
				store.commit("setAddress_mutation", res)
				uni.setStorageSync("address", JSON.stringify(res))
			},
			fail: function(err) {
				uni.getSystemInfo({
					success: (sys) => {
						if (sys.platform == 'ios') {
							plus.runtime.openURL(
								"app-settings://");
						} else {
							var main = plus.android
								.runtimeMainActivity();
							var Intent = plus.android
								.importClass(
									"android.content.Intent");
							//可能应该直接进入应用列表的权限设置？=> android.settings.APPLICATION_SETTINGS
							var mIntent = new Intent(
								'android.settings.LOCATION_SOURCE_SETTINGS'
							);
							main.startActivity(mIntent);
						}
					}
				})
			}
		});
		// #endif
		// #ifdef H5
		uni.getLocation({
			type: 'wgs84',
			success: async function(lb) {
				let res = await analysisAddress({longitude:lb.longitude,latitude:lb.latitude});
				let obj = {}
				if(res.code === 1){
					obj.address={
						city: res.data.city,
					}
					obj.errMsg = "ok";
					resolve(obj);
					store.commit("setAddress_mutation", obj)
					uni.setStorageSync("address", JSON.stringify(obj))
				}
			}
		})
		// #endif
	})
}
export {
	isEmpty,
	msg,
	expressionUrl,
	systemInfo,
	prohibitDebug,
	sliceNumber,
	encodeUnicode,
	decodeUnicode,
	randomStr,
	sleep,
	currencyType,
	formatDate,
	formatTime,
	powerType,
	platformType,
	formatDateDay,
	moneyType,
	browserType,
	formatDateObj,
	getPosition
}
